#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import json
import math

import parsel
import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class HenanZhumadianPolicy(BaseTaxPolicySpider):
    name = 'henan_zhumadian3_policy'

    province = '河南省'
    city = '驻马店市'
    # county = '滑县'
    park = ''

    custom_settings = {
        "DOWNLOAD_TIMEOUT": 60
    }
    headers = {
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
        # "X-Requested-With": "XMLHttpRequest"
    }

    def start_requests(self):
        for source, county, url in [
            ['驻马店市驿城区人民政府', "驿城区", "http://www.zmdycq.gov.cn/html/site_gov/welcome/list02-xxgk.html?id=4262&page=1"],
            ['驻马店市驿城区人民政府', "驿城区", "http://www.zmdycq.gov.cn/html/site_gov/welcome/list02-xxgk.html?id=4289&page=1"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_content, meta={'item': item}, dont_filter=True)

    def parse_content(self, response, **kwargs):
        url = response.urljoin(f"/html/site_gov/welcome/xxgk_list.php?classid={response.url.split('id=')[-1]}")

        meta = response.meta
        yield scrapy.FormRequest(url, callback=self.parse_list, meta=meta, headers=self.headers,
                                 method="POST", dont_filter=True)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        page = response.meta.get('page', 1)
        html = parsel.Selector(text=response.json()['xxgk'])
        elem_list = html.xpath(
            "//li//a[@href]/parent::li[string-length(string(.))>=5]"
        )
        for elem in elem_list:
            item = Item()
            item['source_url'] = '/html/site_gov/welcome/xxgk_details.php?id=' + elem.xpath(""".//a/@href""").re_first('id=(.*)')
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
            #     continue
            if 'relativeInfo' in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        pages = parsel.Selector(text=response.json()['page'])
        next_url = pages.xpath(
            """//a[text()='下页' or ./text()='下页>' or text()='»' or contains(./text(), '下一页') or text()='下一页»']/@href""").get()

        if next_url and next_url not in ['javascript:void(0);'] and response.urljoin(next_url) != response.url:
            url = response.url.replace(f"&page={page}", f"&page={page+1}")
            print(response.url, 'next_url', url)
            page += 1
            yield response.follow(url, callback=self.parse_list, method="POST", meta={'item': prev_item, "page": page})
        else:
            print(response.url, 'not next_url')

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.json()['xtitle']
        item['publish_date'] = response.json()['xtime']
        item['content'] = response.json()['xsyh'] + response.json()['xcontent']
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl henan_zhumadian3_policy".split())
